<template>
  <base-layout @tenant-change="changeTenant" simple>
    <article class="base-layout__inner column">
      <!-- 查询条件 -->
      <t-form ref="form" :data="queryParams" label-width="80px" layout="inline">
        <t-row>
          <t-col :span="3">
            <t-form-item label="疾病分类">
              <t-select
                v-model="queryParams.categoryId"
                placeholder="请选择疾病分类"
                :loading="diseaseCategoryLoading"
                clearable
                style="width: 158px"
              >
                <t-option
                  v-for="category in diseaseCategoryList"
                  :key="category.id"
                  :value="category.id"
                  :label="category.name"
                >
                  {{ category.name }}
                </t-option>
              </t-select>
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item label="名称">
              <t-input
                v-model="queryParams.name"
                placeholder="请输入名称"
                clearable
                style="width: 100%"
              />
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item label="编码">
              <t-input
                v-model="queryParams.code"
                placeholder="请输入编码"
                clearable
                style="width: 100%"
              />
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item>
              <t-space>
                <t-button theme="primary" @click="handleSearch"> 查询 </t-button>
                <t-button variant="base" @click="handleReset"> 重置 </t-button>
              </t-space>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>

      <!-- 新建推荐知识按钮 -->
      <div>
        <t-button theme="primary" @click="handleCreate">
          <template #icon>
            <t-icon name="add" />
          </template>
          新建推荐知识
        </t-button>
      </div>

      <!-- 推荐内容列表 -->
      <div class="recommend-content-list">
        <t-table
          row-key="id"
          bordered
          height="calc(100vh - 55px - 28px - 28px - 88px - 16px - 64px)"
          :data="recommendList"
          :columns="columns"
          :loading="loading"
          :pagination="pagination"
          @page-change="onPageChange"
        >
          <!-- 状态列 -->
          <template #status="{ row }">
            <t-tag :theme="row.status === 1 ? 'success' : 'warning'">
              {{ row.status === 1 ? '已发布' : '未发布' }}
            </t-tag>
          </template>

          <!-- 浏览数格式化 -->
          <template #viewCount="{ row }">
            <span>{{ Number(row.viewCount || 0).toLocaleString() }}</span>
          </template>

          <!-- 点赞数格式化 -->
          <template #likeCount="{ row }">
            <span>{{ Number(row.likeCount || 0).toLocaleString() }}</span>
          </template>

          <!-- 收藏数格式化 -->
          <template #collectCount="{ row }">
            <span>{{ Number(row.collectCount || 0).toLocaleString() }}</span>
          </template>

          <!-- 分享数格式化 -->
          <template #shareCount="{ row }">
            <span>{{ Number(row.shareCount || 0).toLocaleString() }}</span>
          </template>

          <!-- 操作列 -->
          <template #op="{ row }">
            <span>
              <t-button theme="primary" variant="text" @click="handleEdit(row)"> 编辑 </t-button>
              <t-button theme="danger" variant="text" @click="handleDelete(row)"> 删除 </t-button>
            </span>
          </template>
        </t-table>
      </div>
    </article>

    <!-- 推荐知识抽屉 -->
    <recommend-drawer
      v-model="recommendDrawerVisible"
      :edit-data="currentEditData"
      @success="handleDrawerSuccess"
    />
  </base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import { mapGetters } from 'vuex';
import { getDiseaseList } from '@/api/disease';
import { getRecommendPage } from '@/api/recommend';
import { deleteArticleContent } from '@/api/catalog';
import RecommendDrawer from './recommend-drawer.vue';
import { DialogPlugin as TDialog } from 'tdesign-vue';

export default {
  name: 'OperationKnowledgeRecommend',
  components: {
    BaseLayout,
    RecommendDrawer,
  },
  data() {
    return {
      diseaseCategoryLoading: false,
      // 疾病分类相关
      diseaseCategoryList: [],

      // 推荐内容相关
      loading: false,
      recommendList: [],

      // 查询参数
      queryParams: {
        categoryId: null,
        name: '',
        code: '',
      },

      // 表格相关
      columns: [
        { colKey: 'name', title: '标题', width: 300 },
        { colKey: 'code', title: '编码', width: 200 },
        {
          colKey: 'category',
          title: '疾病',
          width: 150,
          cell: (h, {row}) => {
            return h('span', this.getCategoryName(row?.category?.id ?? null));
          },
        },
        { colKey: 'author', title: '作者', width: 150 },
        { colKey: 'viewCount', title: '浏览数', width: 100, align: 'center' },
        { colKey: 'likeCount', title: '点赞数', width: 100, align: 'center' },
        { colKey: 'collectCount', title: '收藏数', width: 100, align: 'center' },
        { colKey: 'shareCount', title: '分享数', width: 100, align: 'center' },
        { colKey: 'createdAt', title: '创建时间', width: 200 },
        { colKey: 'op', title: '操作', width: 160, fixed: 'right' },
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showJumper: true,
        showPageSize: true,
        pageSizeOptions: [10, 20, 50, 100],
      },
      recommendDrawerVisible: false,
      currentEditData: null,
    };
  },
  computed: {
    ...mapGetters(['user/tenantId', 'user/isSuperAdmin']),
    // 添加安全的getter访问
    tenantId() {
      return this.$store.getters['user/tenantId'] || null;
    },
    isSuperAdmin() {
      return this.$store.getters['user/isSuperAdmin'] || false;
    },
  },
  mounted() {
    this.loadDiseaseCategoryList();
    this.loadRecommendList();
  },
  methods: {
    // 获取疾病分类名称
    getCategoryName(categoryId) {
      if (!categoryId) return '-';
      const category = this.diseaseCategoryList.find((item) => item.id === categoryId);
      return category ? category.name : '-';
    },

    // 租户变更处理
    changeTenant(tenantId) {
      // 租户变更时重新加载疾病分类和推荐内容
      this.queryParams = {
        categoryId: null,
        name: '',
        code: '',
      };
      this.recommendList = [];
      this.loadDiseaseCategoryList();
      this.loadRecommendList();
    },

    // 加载疾病分类列表
    async loadDiseaseCategoryList() {
      this.diseaseCategoryLoading = true;
      try {
        const res = await getDiseaseList();
        this.diseaseCategoryList = res?.data?.data || [];
      } catch (error) {
        console.error('加载疾病分类失败:', error);
        this.$message.error('加载疾病分类失败');
        this.diseaseCategoryList = [];
      } finally {
        this.diseaseCategoryLoading = false;
      }
    },

    // 加载推荐内容列表
    async loadRecommendList() {
      this.loading = true;

      try {
        const params = {
          categoryId: this.queryParams.categoryId,
          name: this.queryParams.name,
          code: this.queryParams.code,
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
        };

        const res = await getRecommendPage(params);

        // 根据实际返回的数据结构处理数据
        // axios返回的完整response对象结构: { data: { data: { data: [...], total: 427, page: 1, pageSize: 10 } } }
        if (res && res.data && res.data.data) {
          this.recommendList = Array.isArray(res.data.data.data) ? res.data.data.data : [];
          this.pagination.total = Number(res.data.data.total) || 0;
          // 可选：同步其他分页信息
          this.pagination.current = Number(res.data.data.page) || this.pagination.current;
          this.pagination.pageSize = Number(res.data.data.pageSize) || this.pagination.pageSize;
        } else {
          this.recommendList = [];
          this.pagination.total = 0;
        }
      } catch (error) {
        console.error('加载推荐内容失败:', error);
        this.$message.error('加载推荐内容失败');
        this.recommendList = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 分页变化处理
    onPageChange({current, pageSize}) {
      this.pagination.current = current;

			if (pageSize !== this.pagination.pageSize) {
				this.pagination.current = 1;
			}

			this.pagination.pageSize = pageSize;

      this.loadRecommendList();
    },

    // 排序变化处理
    onSortChange(sortParams) {
      // 确保参数存在且是对象，避免解构失败
      if (!sortParams || typeof sortParams !== 'object') {
        console.warn('排序参数无效:', sortParams);
        return;
      }

      const { sortBy, descending } = sortParams;
      // TODO: 实现排序逻辑
      console.log('排序变化:', sortBy, descending);
    },

    // 编辑推荐内容
    handleEdit(row) {
      this.currentEditData = row;
      this.recommendDrawerVisible = true;
    },

    // 删除推荐内容
    async handleDelete(row) {
      // 基本验证
      if (!row || !row.id) {
        this.$message.error('无效的数据');
        return;
      }

      const confirmMessage = `确定要删除推荐内容"${row.name}"吗？`;
      const warningMessage = '删除后不可恢复。';

      try {
        // 使用TDesign推荐的确认对话框
        const confirmDialog = await new Promise((resolve) => {
          const instance = TDialog.confirm({
            header: '确认删除',
            body: () => {
              return this.$createElement(
                'div',
                {
                  style: {
                    lineHeight: '1.6',
                  },
                },
                [
                  this.$createElement(
                    'p',
                    {
                      style: {
                        margin: '0 0 8px 0',
                        color: '#333',
                      },
                    },
                    confirmMessage
                  ),
                  this.$createElement(
                    'p',
                    {
                      style: {
                        margin: '0',
                        color: '#ff4d4f',
                        fontWeight: '500',
                      },
                    },
                    warningMessage
                  ),
                ]
              );
            },
            confirmBtn: {
              content: '确定删除',
              theme: 'danger',
              loading: false,
            },
            cancelBtn: '取消',
            onConfirm: () => {
              resolve(instance);
            },
            onCancel: () => {
              resolve(null);
            },
          });
        });

        // 用户取消删除
        if (!confirmDialog) {
          return;
        }

        // 显示删除按钮加载状态
        confirmDialog.update({
          confirmBtn: {
            content: '删除中...',
            theme: 'danger',
            loading: true,
          },
        });

        // 调用删除API
        const res = await deleteArticleContent(row.id);

        if (res?.data?.code === 200) {
          confirmDialog.hide();
          this.$message.success(`成功删除推荐内容"${row.name}"`);
          // 重新加载推荐内容列表
          await this.loadRecommendList();
        } else {
          throw new Error(res?.data?.message || '删除失败');
        }
      } catch (error) {
        console.error('删除推荐内容失败:', error);

        // 根据错误类型显示不同的错误信息
        let errorMessage = '删除失败';
        if (error.message) {
          errorMessage = error.message;
        } else if (error.response?.data?.message) {
          errorMessage = error.response.data.message;
        } else if (error.response?.status === 403) {
          errorMessage = '没有权限删除此内容';
        } else if (error.response?.status === 409) {
          errorMessage = '该内容正在被使用，无法删除';
        } else if (error.code === 'NETWORK_ERROR') {
          errorMessage = '网络连接失败，请检查网络后重试';
        }

        this.$message.error(errorMessage);

        // 如果对话框还存在，隐藏它
        if (confirmDialog) {
          confirmDialog.hide();
        }
      }
    },

    // 查询处理
    async handleSearch() {
      this.pagination.current = 1; // 重置到第一页
      await this.loadRecommendList();
    },

    // 重置处理
    handleReset() {
      this.queryParams = {
        categoryId: null,
        name: '',
        code: '',
      };
      this.pagination.current = 1; // 重置到第一页
      this.loadRecommendList();
    },

    // 新建推荐知识
    handleCreate() {
      this.currentEditData = null;
      this.recommendDrawerVisible = true;
    },

    // 抽屉成功处理
    handleDrawerSuccess() {
      this.loadRecommendList();
    },
  },
};
</script>

<style lang="less" scoped>
.search-form-container {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e7e7e7;
  margin-bottom: 16px;
}

.recommend-content-container {
  flex: 1;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #e7e7e7;
  overflow: hidden;

  .recommend-content-header {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #e7e7e7;
    background-color: #fafafa;
  }

  .recommend-content-list {
    padding: 16px;
    min-height: 200px;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  min-height: 200px;

  .empty-icon {
    margin-bottom: 16px;
    color: #ddd;
  }

  .empty-text {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 500;
    color: #666;
  }

  .empty-desc {
    margin: 0;
    font-size: 14px;
    color: #999;
    line-height: 1.5;
  }
}
</style>
